﻿using System;
using System.IO;
using System.Runtime.InteropServices;

namespace SystemModule
{
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1, Size = 28)]
    public class TRecordHeader
    {
        /// <summary>
        /// 是否删除
        /// </summary>
        public bool boDeleted;
        /// <summary>
        /// ID
        /// </summary>
        public byte nSelectID;
        /// <summary>
        /// 是否英雄
        /// </summary>
        public bool boIsHero;
        /// <summary>
        /// 职业
        /// </summary>
        public byte btJob;
        /// <summary>
        /// 最后登录时间
        /// </summary>
        public double dCreateDate;
        public string sName;//15

        public TRecordHeader()
        { }

        public TRecordHeader(byte[] buff)
        {
            this.boDeleted = BitConverter.ToBoolean(buff, 0);
            this.nSelectID = (byte)BitConverter.ToInt32(buff, 1);
            this.boIsHero = BitConverter.ToBoolean(buff, 2);
            this.btJob = (byte)BitConverter.ToInt16(buff, 3);
            this.dCreateDate = BitConverter.ToDouble(buff, 4);
            this.sName = System.Text.Encoding.Default.GetString(buff, 13, 15).Replace("\0", "");
        }

        public byte[] ToByte()
        {
            using (var memoryStream = new MemoryStream())
            {
                var backingStream = new BinaryWriter(memoryStream);

                backingStream.Write(boDeleted);
                backingStream.Write(nSelectID);
                backingStream.Write(boIsHero);
                backingStream.Write(btJob);
                backingStream.Write(dCreateDate);

                int nameLen = 0;
                byte[] nameBuff = HUtil32.StringToByteAry(sName, out nameLen);
                nameBuff[0] = (byte)nameLen;
                Array.Resize(ref nameBuff, 16);
                backingStream.Write(nameBuff);

                var stream = backingStream.BaseStream as MemoryStream;
                return stream.ToArray();
            }
        }
    }
}